import Vue from 'vue'
import Router from 'vue-router'
import proRouterArr from './productRouter';
import store from '../stores/stores.js'
import indexApi from "./../globalApi/indexApi.js";
import md5 from 'js-md5';
/*import axios from "axios";*/

//布局组件
const TheContainer = () => import('@/containers/TheContainer')
const Page404 = () => import('@/template/pages/Page404.vue')
const Page500 = () => import('@/template/pages/Page500')
const login = () => import('@/views/login/login')
const totalRouter = [{
  path: '/login',
  name: 'login',
  component: login
},

{
  //注意使用方式:会把TheContainer组件渲染在根标签上,adminHome是children标签放在TheContainer组件的<router-view>上
  path: '/',
  redirect: '/adminHome',
  // redirect: token ? '/adminHome' : '/pages/login',
  name: 'home',
  component: TheContainer,
  children: proRouterArr
},
{
  path: '/pages',
  redirect: '/pages/404',
  name: 'Pages',
  component: {
    render(c) {
      //return c( 'keep-alive',{},[c("router-view",{},)] )
      return c('router-view')
    }
  },
  children: [{
    path: '404',
    name: 'Page404',
    component: Page404
  },
  {
    path: '500',
    name: 'Page500',
    component: Page500
  },
  {
    path: 'login',
    name: 'login',
    component: login
  },
  ]
},
{
  path: '*',
  redirect: '/pages'
}
];


Vue.use(Router);

// 获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


// 全局路由钩子
const router = new Router({
  mode: 'hash',
  linkActiveClass: 'active',
  scrollBehavior: () => ({
    y: 0
  }),
  routes: totalRouter
});

router.beforeEach((to, from, next) => {
  const user = store.state.user;
  let isLogin = store.state.isLogin;
  const lastRoute = store.state.lastRoute;
  // loginByToken(to); //外部接入系统，当前用户采用传入的为主，没有则按照正常来  目前产品不涉及 项目中心客户在使用


  // start 通过url 传入用户名密码直接后端登录 然后前端隐藏用户名和密码 
  loginByUrl(to);
  if (to.query.redirect !== "otherLogin" && to.fullPath.indexOf('userName') != -1) {
    let fullPath = to.fullPath.substring(0, to.fullPath.indexOf("?"));
    router.replace({
      path: fullPath,
      query: {
        redirect: 'otherLogin'
      }
    });
  }

  //跳转到登陆界面  浏览器中 ''不等于null==undefined
  if (from.name === "login" && lastRoute != '' && lastRoute && isLogin) {
    if (to.query.redirect !== "login" && lastRoute !== "/pages/login") {
      router.replace({
        path: lastRoute,
        query: {
          redirect: router.currentRoute.name
        }
      });
    }
  }

  if (to.name == "login") {
    next()
  }


  if (to.name === "commonProcess" || to.name === "commonQualityCheck") {
    let result = true;
    result = isShowProcessModal(to.params.id, user);
    if (!result) return
    else next()
  } else next()


});

export default router;


function isShowProcessModal(id, user) {
  //  添加cooike
  var acookie = document.cookie.split("; ");
  let getck = (sname) => { //获取单个cookies
    for (var i = 0; i < acookie.length; i++) {
      var arr = acookie[i].split("=");
      if (sname == arr[0]) {
        if (arr.length > 1)
          return arr[1];
        else
          return "";
      }
    }
    return "";
  }
  let xcookie = getck("engine-token");


  let path = indexApi.processingApi.systemQuery // query(liu的接口)  search(zhu的接口)
  let result = true
  let param = {
    groupId: id,
    systemId: systemId
  };
  $.ajax({
    type: "GET",
    async: false, // fasle同步，true异步
    headers: {
      Authorization: user != null ? user.token : "",
      "x-token": `${xcookie}`
    },
    contentType: "application/json;charset=UTF-8",
    url: path,
    data: param,
    success: function (res) {
      if (res.success && res.code == 0) {
        if (res.data.length < 1) result = false
      } else {
        result = false
      }
      // if (res.message === "success" && res.code == 0) {
      //   if (res.data.length < 1) result = false
      // }
      // else {
      //   result = false
      // }
    },
    error: function (e) {
      console.log(e.status);
    }
  });
  return result
}

function loginByToken(to) {
  let flag = true;
  let token = GetQueryString(to, "token");
  if (token != "" && token != null) {
    flag = getToken(token);
  }

  if (!flag) {
    // alert("用户名和密码验证失败，请您确认，并即将跳转登陆界面！")
    router.push({
      path: '/pages/login',
    })
  }
}

function loginByUrl(to) {

  // http://localhost:8080/#/adminHome?userName=03&pwd=Ndrcc@03
  ///adminHome?01&123456
  //let fullpath=to.fullPath;
  let arrSplit = to.fullPath.split("?");
  if (arrSplit.length <= 1) {
    return;
  }

  // to.fullPath = to.fullPath.substring(0, to.fullPath.indexOf("?"));

  let route = arrSplit[0];
  let user = arrSplit[1];
  let arrUser = user.split("&");
  if (arrUser.length != 2) {
    return;
  }
  let userNames = arrUser[0].split("=");
  if (userNames.length != 2) {
    return;
  }

  let username = "";
  if (userNames[0] == "userName") {
    username = userNames[1];
  } else if (userNames[1] == "userName") {
    username = userNames[0];
  } else {
    return;
  }

  let passwords = arrUser[1].split("=");
  if (passwords.length != 2) {
    return;
  }

  let password = "";
  if (passwords[0] == "pwd") {
    password = passwords[1];
    password = password.replace('%40', '@');
  } else if (passwords[1] == "pwd") {
    password = passwords[0];
    password = password.replace('%40', '@');
  } else {
    return;
  }
  // console.log("第三方用户登录",username,password);
  let path = indexApi.homeLoginOthers.login;
  let result = false;
  let param = {
    username: username,
    password: md5(password),
    // isMd5: false,
    encrypt: true,
    systemId: systemId,
  };
  // console.log("第三方用户登录加密",param);
  $.ajax({
    type: "post",
    async: false, // fasle同步，true异步
    headers: {
      Authorization: ""
    },
    contentType: "application/json;charset=UTF-8",
    url: path,
    data: JSON.stringify(param),
    success: function (res) {
      if (res.success && res.code == 0) {
        console.log("LoginByUrl接口返回接口：" + JSON.stringify(res.data))
        result = true;

        saveUserInfoSTHX(res.data)
      } else
        result = false
    },
    error: function (e) {
      console.log(e.status);
    }
  });
  if (!result) {
    alert("用户名和密码验证失败，请您确认，并即将跳转登陆界面！")
    router.push({
      path: '/pages/login',
    })
  }


}

function GetQueryString(to, name) {
  var context = "";
  let reg = '[?|&]' +
    name + '=' + '([^&;]+?)(&|#|;|$)';
  // location.href
  context = decodeURIComponent((new RegExp(reg).exec(to.fullPath) || [, ""])[1].replace(/\+/g, '%20')) || null
  return context == null || context == "" || context == "undefined" ? "" : context;
}

function getToken(token) {
  let path = indexApi.homeLoginOthers.loginByToken;
  let result = false;
  let param = {
    token: token,
  };

  $.ajax({
    type: "GET",
    async: false, // fasle同步，true异步
    headers: {
      Authorization: ""
    },
    contentType: "application/json;charset=UTF-8",
    url: path,
    data: param,
    success: function (res) {
      if (res.success && res.code == 0) {
        console.log("LoginByToken接口返回接口：" + JSON.stringify(res.data))
        result = true;
        saveUserInfoSTHX(res.data)
      } else {
        result = false;
        alert(res.message);
      }

    },
    error: function (e) {
      console.log(e.status);
    }
  });
  return result;
}

function saveUserInfoSTHX(result) {
  let user = {
    userName: result.userData.userName,
    userId: result.userData.userId,
    token: result.token,
    department: result.userData.organizationName,
    nickName: result.userData.nickName
  };
  store.dispatch("login", user); //将user保存到store中
}






/*
const isProduction = process.env.NODE_ENV == 'production'

import Vue from 'vue'
import Router from 'vue-router'
import proRouterArr from './productRouter';
// import Loading from '@/plugins/loading';
import {
  cilDoubleQuoteSansRight
} from '@coreui/icons';

import store from '../stores/stores.js'
// import  http from './utils/http'

import urlPath from "./../globalApi/urlPath.js"

// Vue.use(Loading)
// const docRouterArr = isProduction ? [] : require('./docRouter'); // 开发环境需要文档时打开此项
// 布局组件
const TheContainer = () => import('@/containers/TheContainer')
// 公用页面
const Page404 = () => import('@/template/pages/Page404.vue')
const Page500 = () => import('@/template/pages/Page500')
const Login = () => import('@/views/login/Login')


const Model = () => import('@/views/modelManage/Model');
const dataQueryModel = () => import('@/views/modelManage/dataQueryModel'); //生产线流程

Vue.use(Router)
// coreUi提供的路由
const docRouter = []

// 生产环境不需要文档router 包含layout的页面路由
const childrenRouter = isProduction ? proRouterArr : docRouter.concat(proRouterArr)

// 整合路由 组件  +  异常页面
function configRoutes() {
  return [{
      path: 'login',
      name: 'Login',
      component: Login
    },
    {
      path: '/elevenModel',
      name: 'elevenModel',
      component: Model
    },
    {
      path: '/dataQueryModel',
      name: 'dataQueryModel',
      component: dataQueryModel
    },
    {
      //注意使用方式:会把TheContainer组件渲染在根标签上,adminHome是children标签放在TheContainer组件的<router-view>上
      path: '/',
      redirect: '/adminHome',
      // redirect: token ? '/adminHome' : '/pages/login',
      name: 'Home',
      component: TheContainer,
      children: childrenRouter
    },
    {
      path: '/pages',
      redirect: '/pages/404',
      name: 'Pages',
      component: {
        render(c) {
          return c('router-view')
        }
      },
      children: [{
          path: '404',
          name: 'Page404',
          component: Page404
        },
        {
          path: '500',
          name: 'Page500',
          component: Page500
        },
        {
          path: 'login',
          name: 'Login',
          component: Login
        },
      ]
    },
    {
      path: '*',
      redirect: '/pages'
    }
  ]
}




// 全局路由钩子
const router = new Router({
  mode: 'hash',
  linkActiveClass: 'active',
  scrollBehavior: () => ({
    y: 0
  }),
  routes: configRoutes()
})

router.beforeEach((to, from, next) => {
  const user = store.state.user;
  let isLogin = store.state.isLogin;
  const lastRoute = store.state.lastRoute;

  loginByToken(to); //外部接入系统，当前用户采用传入的为主，没有则按照正常来
  //跳转到登陆界面
  if (from.name === "Login" && lastRoute && isLogin) {
    if (to.query.redirect !== "Login") {
      router.replace({
        path: lastRoute,
        query: {
          redirect: router.currentRoute.name
        }
      });
    }
  }

  if (to.name == "Login") {
    next()
  }

  if (to.name === "commonProcess" || to.name === "commonQualityCheck") {
    let result = true
    result = isShowProcessModal(to.params.id, user)
    if (!result) return
    else next()
  } else
    next()
})




function isShowProcessModal(id, user) {
  let path = urlPath.productManage.query // query(liu的接口)  search(zhu的接口)
  let result = true
  let param = {
    groupId: id,
    systemId: systemId
  };
  $.ajax({
    type: "GET",
    async: false, // fasle同步，true异步
    headers: {
      Authorization: user != null ? user.token : ""
    },
    contentType: "application/json;charset=UTF-8",
    url: path,
    data: param,
    success: function (res) {
      if (res.success && res.code == 0) {
        if (res.data.length < 1) result = false
      } else {
        result = false
      }
      // if (res.message === "success" && res.code == 0) {
      //   if (res.data.length < 1) result = false
      // }
      // else {
      //   result = false
      // }
    },
    error: function (e) {
      console.log(e.status);
    }
  });
  return result
}

function loginByToken(to) {
  let flag = true;
  let token = GetQueryString(to, "token");
  if (token != "" && token != null) {
    flag = getToken(token);
  }


  if (!flag) {
    // alert("用户名和密码验证失败，请您确认，并即将跳转登陆界面！")
    router.push({
      path: '/pages/login',
    })
  }
}

function GetQueryString(to, name) {
  var context = "";
  let reg = '[?|&]' +
    name + '=' + '([^&;]+?)(&|#|;|$)';
  // location.href
  context = decodeURIComponent((new RegExp(reg).exec(to.fullPath) || [, ""])[1].replace(/\+/g, '%20')) || null
  return context == null || context == "" || context == "undefined" ? "" : context;
}

function getToken(token) {
  let path = urlPath.login_api.loginByToken;
  let result = false;
  let param = {
    token: token,
  };

  $.ajax({
    type: "GET",
    async: false, // fasle同步，true异步
    headers: {
      Authorization: ""
    },
    contentType: "application/json;charset=UTF-8",
    url: path,
    data: param,
    success: function (res) {
      if (res.success && res.code == 0) {
        console.log("LoginByToken接口返回接口：" + JSON.stringify(res.data))
        result = true;
        saveUserInfoSTHX(res.data)
      } else {
        result = false;
        alert(res.message);
      }

    },
    error: function (e) {
      console.log(e.status);
    }
  });
  return result;
}

function saveUserInfoSTHX(result) {
  let user = {
    userName: result.userData.userName,
    userId: result.userData.userId,
    token: result.token,
    department: result.userData.organizationName,
    nickName: result.userData.nickName
  };
  store.dispatch("login", user); //将user保存到store中
}


export default router;
*/